<?php
/**
 * Created by PhpStorm.
 * User: 万奇
 * Date: 2020/11/29 0029
 * Time: 23:15
 */

namespace app\admin\controller\v1;


use app\admin\model\WxkCustomerFollow;
use app\Request;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use think\App;
use think\facade\Db;

class WxkCustomer extends BasicController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 客户互动轨迹列表
     * User: 万奇
     * Date: 2021/7/6 17:36
     * @throws \think\db\exception\DbException
     */
    public function get_customer_track_list(){
        param_receive(['external_user_id', 'page', 'limit']);

        $customer = new \app\admin\model\WxkCustomerTrack();
        $result = $customer->get_customer_track_list($this->param);

        response(200, '', $result['data'], $result['total']);
    }

    /**
     * 客户跟进记录列表
     * User: 万奇
     * Date: 2021/3/25 0025
     * @throws \think\db\exception\DbException
     */
    public function get_customer_follow_list(){
        param_receive(['external_user_id', 'follow_userid', 'page', 'limit']);

        $customer = new \app\admin\model\WxkCustomerFollow();
        $result = $customer->get_customer_follow_list($this->param);

        response(200, '', $result['data'], $result['total']);
    }

    /**
     * 添加客户跟进
     * User: 万奇
     * Date: 2021/7/6 17:36
     * @throws \think\db\exception\DbException
     */
    public function add_customer_follow(){
        param_receive(['external_user_id', 'follow_userid', 'add_follow_user', 'follow_type', 'content']);
        $customer = new \app\admin\model\WxkCustomerFollow();
        $customer->add_customer_follow($this->param, 1);

        response(200, '操作成功');
    }

    /**
     * 上传客户画像
     * User: 万奇
     * Date: 2021/7/6 17:36
     */
    public function upload_customer_portrait_photo(){
        $result         = upload_photo('photo');

        response(200, '操作成功', $result);
    }

    /**
     * 回显编辑客户画像
     * User: 万奇
     * Date: 2021/4/30 0024
     */
    public function show_edit_customer_portrait(){
        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->show_edit_customer_portrait();

        response(200, '', $result);
    }

    /**
     * 获取客户画像
     * User: 万奇
     * Date: 2021/4/28 0023
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_customer_portrait(){
        param_receive(['external_user_id']);
        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->get_customer_portrait($this->param);

        response(200, '', $result);
    }

    /**
     * 修改客户详情
     * User: 万奇
     * Date: 2021/3/23 0023
     * @throws \think\db\exception\DbException
     */
    public function edit_customer_info(){
        param_receive(['follow_userid', 'external_user_id']);
        $customer = new \app\admin\model\WxkCustomer();
        $customer->edit_customer_info($this->param, $this->user_info['user_id'], 1);

        response(200, '操作成功');
    }

    /**
     * 获取客户详情
     * User: 万奇
     * Date: 2021/3/23 0023
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_customer_info(){
        param_receive(['id']);
        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->get_customer_info($this->param);

        response(200, '', $result);
    }

    /**
     * 客户打标签/移除标签
     * User: 万奇
     * Date: 2021/1/15 0015
     */
    public function customer_tagging(){
        param_receive(['id', 'tag_ids', 'type']);
        $customer = new \app\admin\model\WxkCustomer();
        $customer->customer_tagging($this->param, $this->user_info['user_id'], 1);

        response(200, '操作成功');
    }

    /**
     * 客户打标签回显已有的标签
     * User: 万奇
     * Date: 2021/1/14 0014
     */
    public function show_customer_tag(){
        param_receive(['id', 'type']);

        $this->param['table_name']   = isset($param['not_qw']) ? 'enter_customer' : 'wxk_customer';

        $result = (new \app\admin\model\WxkCustomer())->show_customer_tag($this->param);

        response(200, '', $result);
    }

    /**
     * 重复客户列表
     * User: 万奇
     * Date: 2021/1/14 0014
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function repeat_list_customer(){
        param_receive(['page', 'limit']);

        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->repeat_list_customer($this->param);

        response(200, '', $result['data'], $result['count']);
    }

    /**
     * 客户列表渲染
     * User: 万奇
     * Date: 2021/1/14 0014
     */
    public function show_list_customer(){
        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->show_list_customer();

        response(200, '', $result);
    }

    /**
     * 客户列表
     * User: 万奇
     * Date: 2020/12/3 0003
     * @throws \think\db\exception\DbException
     */
    public function get_list_customer()
    {
        param_receive(['page', 'limit']);

        $customer = new \app\admin\model\WxkCustomer();
        $result = $customer->get_list_customer($this->param);

        response(200, '', $result['data'], $result['count']);
    }

    /**
     * 同步企业微信客户
     * User: 万奇
     * Date: 2020/12/4 0004
     * @throws \think\db\exception\DbException
     */
    public function synchro_customer()
    {
        // 同步客户标签
        $wechat_user = new \app\admin\model\WxkCustomerTag();
        $wechat_user->synchro_customer_tag();

        // 同步客户
        $wechat_user = new \app\admin\model\WxkCustomer();
        $wechat_user->synchro_customer();

        response(200, '操作成功');
    }
    /**
     * 线索列表
     * User: 李宁
     * Date: 2020/12/3 0003
     * @throws \think\db\exception\DbException
     */
    public function get_leads_list(){
        $where = [];
        $admin = $this->user_info;
        $param = $this->param;

        if (is_exists($param['add_way'])) {
            if($param['add_way'] == 1) {
                $where[] = ['tag_ids', 'like', "%et2KBLHwAAXl8dzhu-gzW69njwSkzUIw%"];
            }else{
                $where[] = ['tag_ids', 'not like', "%et2KBLHwAAXl8dzhu-gzW69njwSkzUIw%"];
            }
        }
        if ($admin['role_id'] == '106a9731-838e-23d3-0fd3-b0800dd352bf') {
            $where[] = ['c.follow_userid', '=', $admin['userid']];
        }
        if ($admin['role_id'] == 'b9115062-e965-a34d-ed14-9fb7f9a742a3') {
            $where[] = ['c.follow_userid', 'in', ['huayunlong','zhangguoqing','wangshuo']];
        }

        if (is_exists($param['keyword'])) {
            $where[] = ['c.name|c.follow_remark|c.follow_remark_mobiles', 'like', "%{$param['keyword']}%"];
        }
        if (is_exists($param['follow_userid'])) {
            $where[] = ['c.follow_userid', '=', $param['follow_userid']];
        }
        if (is_exists($param['follow_status'])) {
            $where[] = ['c.follow_status', '=', $param['follow_status']];
        }
        if (is_exists($param['start_time']) && is_exists($param['end_time'])) {
            $where[] = ['c.follow_createtime', 'between', [$param['start_time'], $param['end_time']]];
        }
        $conditions = [];
        if (is_exists($param['tag_ids'])) {
            $tagIdsArray = explode(',', $param['tag_ids']);
            foreach ($tagIdsArray as $tagId) {
                $conditions[] = "FIND_IN_SET('{$tagId}', tag_ids)";
            }
        }
        $list = Db::name('wxk_customer')->alias('c')
            ->leftJoin('wxk_customer_portrait p', 'p.external_user_id = c.external_user_id')
            ->leftJoin('sys_user u', 'u.userid = c.follow_userid')
            ->field('c.id,c.external_user_id,c.name as nickname,c.tag_ids,c.avatar,c.follow_createtime,c.follow_userid,c.follow_add_way,c.follow_status,
            c.follow_remark as real_name,c.follow_remark_company,c.follow_remark_mobiles,p.industry,p.area,
            u.username as admin_name')
            ->where($where)
            ->where(implode(' AND ', $conditions))
            ->order(['c.follow_createtime' => 'desc'])
            ->paginate($param['limit'])->toArray();

        $tag_yl = Db::name('wxk_customer_tag')->where('parent_code',181)->column('name','id');
        $tag_lt = Db::name('wxk_customer_tag')->where('parent_code',174)->column('name','id');
        $tag_sj = Db::name('wxk_customer_tag')->where('parent_code',183)->column('name','id');
        $tag_kh = Db::name('wxk_customer_tag')->where('parent_code',163)->column('name','id');

        $external_user_ids = array_column($list['data'], 'external_user_id');
        $follow_list = Db::name('wxk_customer_follow')
            ->where('external_user_id','in',$external_user_ids)
            ->field('id,external_user_id,follow_userid,content,create_at')
            ->order('id','desc')
            ->select();
        $fu_arr = [];
        foreach ($follow_list as $item) {
            $external_user_id = $item['external_user_id'];
            if (!isset($fu_arr[$external_user_id])) {
                $fu_arr[$external_user_id] = [
                    'first_follow_time' => $item['create_at'],
                    'last_follow_time' => $item['create_at'],
                    'last_follow_notes' => []
                ];
            }
            // 更新最早跟进时间
            if ($item['create_at'] < $fu_arr[$external_user_id]['first_follow_time']) {
                $fu_arr[$external_user_id]['first_follow_time'] = $item['create_at'];
            }
            // 更新最晚跟进时间
            if ($item['create_at'] > $fu_arr[$external_user_id]['last_follow_time']) {
                $fu_arr[$external_user_id]['last_follow_time'] = $item['create_at'];
            }
            // 添加last_followup_notes
            $date = date('m-d',strtotime($item['create_at']));
            $fu_arr[$external_user_id]['last_follow_notes'][] = $date . '：' . $item['content'];
        }
        foreach ($fu_arr as $external_user_id => $data) {
            if($data['last_follow_notes']){
                krsort($data['last_follow_notes']);
                $fu_arr[$external_user_id]['last_follow_notes'] = implode('。', $data['last_follow_notes']);
            }
        }

        foreach ($list['data'] as $k => $v){
//            unset($list['data'][$k]['tag_ids']);
            $list['data'][$k]['tag_yl'] = get_name_attr($tag_yl, $v['tag_ids']);
            $list['data'][$k]['tag_lt'] = get_name_attr($tag_lt, $v['tag_ids']);
            $list['data'][$k]['tag_sj'] = get_name_attr($tag_sj, $v['tag_ids']);
            $list['data'][$k]['tag_kh'] = get_name_attr($tag_kh, $v['tag_ids']);

            if(array_key_exists($v['external_user_id'], $fu_arr)){
                $list['data'][$k]['first_followup_time'] = $fu_arr[$v['external_user_id']]['first_follow_time'];
                $list['data'][$k]['last_follow_time'] = $fu_arr[$v['external_user_id']]['last_follow_time'];
                $list['data'][$k]['last_follow_notes'] = $fu_arr[$v['external_user_id']]['last_follow_notes'];
            }else{
                $list['data'][$k]['first_followup_time'] = '';
                $list['data'][$k]['last_follow_time'] = '';
                $list['data'][$k]['last_follow_notes'] = '';
            }

            $list['data'][$k]['follow_add_way'] = $v['follow_add_way'] ? \StaticData::RESOURCE_NAME['follow_add_way'][$v['follow_add_way']] : \StaticData::RESOURCE_NAME['follow_add_way'][0];
        }
        response(200, '', $list['data'], $list['total']);
    }

    /**
     * 线索详情
     * User: 李宁
     * */
    public function get_leads_info(){
        $param = $this->param;
        $id = $param['id'];
        $data = Db::name('wxk_customer')->alias('c')
            ->leftJoin('wxk_customer_portrait p', 'p.external_user_id = c.external_user_id')
            ->field('c.id,c.external_user_id,c.name as nickname,c.tag_ids,c.avatar,c.follow_createtime,c.follow_userid,c.follow_add_way,c.follow_status,
            c.follow_remark as real_name,c.follow_remark_company,c.follow_remark_mobiles,c.gender,p.industry,p.industry_id,p.area,p.area_id,p.wechat,p.email,p.intention')
            ->find($id);

        $tag_yl = Db::name('wxk_customer_tag')->where('parent_code',181)->column('name','id');
        $tag_lt = Db::name('wxk_customer_tag')->where('parent_code',174)->column('name','id');
        $tag_sj = Db::name('wxk_customer_tag')->where('parent_code',183)->column('name','id');
        $tag_kh = Db::name('wxk_customer_tag')->where('parent_code',163)->column('name','id');

        $data['tag_yl_selected'] = get_ids_attr($tag_yl, $data['tag_ids']);
        $data['tag_lt_selected'] = get_ids_attr($tag_lt, $data['tag_ids']);
        $data['tag_sj_selected'] = get_ids_attr($tag_sj, $data['tag_ids']);
        $data['tag_kh_selected'] = get_ids_attr($tag_kh, $data['tag_ids']);

        response(200, '', $data);
    }
    /**
     * 获取部门成员
     * User: 李宁
     * */
    public function get_user_sales(){
        $admin = $this->user_info;
        $where = [];
        if ($admin['role_id'] == '106a9731-838e-23d3-0fd3-b0800dd352bf') {
            $where[] = ['userid', '=', $admin['userid']];
        }else{
            $where[] = ['userid', 'in', ['huayunlong','zhangguoqing','wangshuo']];
        }
        $data = Db::name('sys_user')
            ->where($where)
            ->column('username,userid');
        response(200, '', $data);
    }
    /**
     * 获取标签树
     * User: 李宁
     * */
    public function get_tags_tree(){
        $data = Db::name('wxk_customer_tag')
            ->where('code','<>',98)
            ->where('parent_code','<>',98)
            ->field('id,code,parent_code,name')
            ->order('code','asc')
            ->select();
        $tree = $this->buildTree($data);
        response(200, '', $tree);
    }
    public function buildTree($list, $pid = 0)
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['parent_code'] == $pid) {
                $children = $this->buildTree($list, $item['code']);
                if ($children) {
                    $item['tags'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    /**
     * 更新标签
     * User: 李宁
     * */
    public function update_tag(){
        $param = $this->param;
        $id = $param['id'];
        $tag_arr = $param['tag_ids'];

        // 检查数据库中是否已存在相同的标签
        $existingTags = Db::name('wxk_customer')
            ->where('id', $id)
            ->column('tag_ids');

        if($existingTags){
            $existingTags = explode(',', $existingTags[0]);
        }
        if($tag_arr){
            $add_tag = array_diff($tag_arr, $existingTags);
            $remove_tag = array_diff($existingTags, $tag_arr);
            $customer = new \app\admin\model\WxkCustomer();
            if (!empty($add_tag)) {
                $params = [
                    'id' => [$id],
                    'tag_ids' => array_values($add_tag),
                    'type' => 1
                ];
                $customer->customer_tagging($params, $this->user_info['user_id'], 1);
            }
            if (!empty($remove_tag)) {
                $params = [
                    'id' => [$id],
                    'tag_ids' => array_values($remove_tag),
                    'type' => 2
                ];
                $customer->customer_tagging($params, $this->user_info['user_id'], 1);
            }
        }
        response(200, '操作成功');
    }
}